﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeddingEventManagement_API;
using WeddingEventManagementApp.Models;

namespace WeddingEventManagementApp.Controllers
{
    public class LocationController : BaseController
    {
        ILocationManager locationManager = null;

        public LocationController()
        {
            locationManager = new LocationManager();
        }

        //
        // GET: /Location/

        public ActionResult Index()
        {
            var model = new LocationMain_VM()
            {
                MostUsed = locationManager.GetMostUsedLocations(5),
                RecentlyViewed = locationManager.GetRecentlyViewedLocations(5)
            };
            return View("Locations", model);
        }

        //
        // GET: /Location/Details/5

        public ActionResult Details(int id)
        {
            var events = new EventManager().GetEventsForLocation(id);
            ViewBag.Events = events;

            decimal average = 0.0M;
            var invoiceManager = new InvoiceManager();
            int count = 0;
            foreach (var item in events.Where(i => i.Invoices.Count() > 0))
	        {
		        foreach (var invoice in item.Invoices)
	            {
                    average += invoiceManager.GetInvoiceTotal(invoice.InvoiceID);
                    count++;
	            }
	        }
            if (count > 0)
                average = average / count;

            ViewBag.AverageCost = average.ToString("c");
            var model = locationManager.GetLocation(id);

            return View("LocationDetails", model);
        }

        public JsonResult GetAllJson()
        {
            var data = locationManager.GetLocations();

            List<object> newList = new List<object>();
            foreach (Location location in data)
            {
                
                newList.Add
                (
                    new
                    {
                        ID = location.LocationID,
                        LocationType = String.IsNullOrEmpty(location.Type) ? "Location" : location.Type,
                        Name = location.Name,
                        Address = String.Format("{0}, {1} {2} {3}", location.StreetAddress, location.City, location.Province, location.PostalCode),
                        Phone = String.IsNullOrEmpty(location.ContactPhone) ? "0" : location.ContactPhone,
                        Email = String.IsNullOrEmpty(location.ContactEmail) ? "0" : location.ContactEmail,
                        Lat = location.Lat,
                        Lng = location.Lng
                    }
                );
            }

            return Json(newList, JsonRequestBehavior.AllowGet);
        }

        // Finds Client and returns as JSON
        public JsonResult Search(string term)
        {
            //// get clients filtered by search term
            List<Location> locations = new LocationManager().GetLocations(term);

            //// tranlate model to viewmodel
            var newlist = new List<AutoCompleteLocations_VM>();
            foreach (var location in locations)
            {
                AutoCompleteLocations_VM l = new AutoCompleteLocations_VM();
                l.ID = location.LocationID;
                l.Name = location.Name;
                l.Address = location.StreetAddress;
                l.City = location.City;
                l.Province = location.Province;

                newlist.Add(l);
            }

            return Json(newlist, JsonRequestBehavior.AllowGet);
        }


        //
        // GET: /Location/Create

        public ActionResult Create()
        {
            ViewBag.DropdownTypes = this.GetLocationVenueTypes();
            return View("AddLocation");
        }

        //
        // POST: /Location/Create

        [HttpPost]
        public ActionResult Create(Location_VM model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    int newId = locationManager.CreateLocation(model.Name, model.StreetAddress, model.City,
                        model.PostalCode, model.Province, model.Lat, model.Lng, model.Type, model.Capacity, model.ContactName, model.ContactPhone, model.ContactEmail,
                        model.Notes, Utility.GetUserID(User.Identity.Name));

                    return RedirectToAction("Details", new { id = newId  });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            return View("AddLocation", model);
        }
        
        //
        // GET: /Location/Edit/5

        public ActionResult Edit(int id)
        {
            Location l = locationManager.GetLocation(id);
            ViewBag.DropdownTypes = this.GetLocationVenueTypes();
            var model = new Location_VM()
            {
                City = l.City,
                ContactEmail = l.ContactEmail,
                ContactName = l.ContactName,
                ContactPhone = l.ContactPhone,
                LocationID = l.LocationID,
                Name = l.Name,
                Type = l.Type,
                Notes = l.Notes,
                PostalCode = l.PostalCode,
                Province = (Province)Enum.Parse(typeof(Province), l.Province, true),
                StreetAddress = l.StreetAddress,
                Website = l.Website,
                Lat = l.Lat,
                Lng = l.Lng,
                Capacity = l.Capacity.HasValue ? l.Capacity.Value : 0
            };

            return View(model);
        }

        //
        // POST: /Location/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, Location_VM model)
        {
            try
            {
                Location l = locationManager.GetLocation(id);
                l.City = model.City;
                l.ContactEmail = model.ContactEmail;
                l.ContactName = model.ContactName;
                l.ContactPhone = model.ContactPhone;
                l.LastUpdated = DateTime.UtcNow;
                l.Notes = model.Notes;
                l.PostalCode = model.PostalCode;
                l.Province = model.Province.ToString();
                l.Name = model.Name;
                l.StreetAddress = model.StreetAddress;
                l.Website = model.Website;
                l.Lat = model.Lat;
                l.Lng = model.Lng;
                l.Type = model.Type;
                l.Capacity = model.Capacity;
                locationManager.UpdateLocation(l, Utility.GetUserID(User.Identity.Name));

                return RedirectToAction("Details", new { id = id });
            }
            catch(Exception e)
            {
                ModelState.AddModelError("xxx", e.Message);
                return View();
            }
        }

        //
        // POST: /Location/Delete/5

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                locationManager.DeleteLocation(id);

                return RedirectToAction("Index");
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException)
            {
                throw;
            }
        }

        /// <summary>
        /// Returns unique location venue types
        /// </summary>
        /// <returns></returns>
        public IEnumerable<SelectListItem> GetLocationVenueTypes()
        {
            var data = locationManager.GetUniqueLocationVenueTypes();
            List<SelectListItem> dropdown = new List<SelectListItem>();

            foreach (string str in data)
            {
                dropdown.Add(new SelectListItem() { Text = str, Value = str });
            }

            return dropdown;
        }

        public ActionResult PhotoUpload(int id, IEnumerable<HttpPostedFileBase> files)
        {
            try
            {
                foreach (var file in files)
                {
                    if (file != null) //check null
                    {
                        // if the file has any contentlength
                        if (file.ContentLength > 0)
                        {
                            // Upload
                            FileInfo fi = new FileInfo(file.FileName);
                            var filename = Guid.NewGuid().ToString() + fi.Extension;
                            var path = Path.Combine(Server.MapPath("~/Content/Uploads"), filename);
                            file.SaveAs(path);

                            // Attach DB Reference
                            locationManager.AddPhoto(new LocationPhoto() { Filename = filename, LocationID = id });
                        }
                    }
                }

                ShowMessage("Photos uploaded successfully", MessageType.Success);
            }
            catch (Exception)
            {
                ShowMessage("Error Uploading Files, please try again", MessageType.Error);
            }

            return RedirectToAction("Details", new { id = id });
        }
    }
}
